var AES = require('./aes');
var CBC = require('./cbc');
var $ = global.bitcore.util.preconditions;
var Random = global.bitcore.crypto.Random;
var Hash = global.bitcore.crypto.Hash;
const Buffer = require('buffer').Buffer;

// Symmetric encryption with AES and CBC convenience class
// eslint-disable-next-line @typescript-eslint/no-empty-function
var AESCBC = function AESCBC() {
    /* do nothing */
};

AESCBC.encrypt = function (messagebuf, passwordstr) {
    $.checkArgument(messagebuf);
    $.checkArgument(passwordstr);
    var cipherkeybuf = Hash.sha256(new Buffer(passwordstr));
    return AESCBC.encryptCipherkey(messagebuf, cipherkeybuf);
};

AESCBC.decrypt = function (encbuf, passwordstr) {
    $.checkArgument(encbuf);
    $.checkArgument(passwordstr);
    var cipherkeybuf = Hash.sha256(new Buffer(passwordstr));
    return AESCBC.decryptCipherkey(encbuf, cipherkeybuf);
};

AESCBC.encryptCipherkey = function (messagebuf, cipherkeybuf, ivbuf) {
    $.checkArgument(messagebuf);
    $.checkArgument(cipherkeybuf);
    $.checkArgument(ivbuf);
    ivbuf = ivbuf || Random.getRandomBuffer(128 / 8);
    var ctbuf = CBC.encrypt(messagebuf, ivbuf, AES, cipherkeybuf);
    return Buffer.concat([ivbuf, ctbuf]);
};

AESCBC.decryptCipherkey = function (encbuf, cipherkeybuf) {
    $.checkArgument(encbuf);
    $.checkArgument(cipherkeybuf);
    var ivbuf = encbuf.slice(0, 128 / 8);
    var ctbuf = encbuf.slice(128 / 8);
    console.log('向量', ivbuf, ctbuf);
    return CBC.decrypt(ctbuf, ivbuf, AES, cipherkeybuf);
};

module.exports = AESCBC;
